<template>
  <slot :open="open">
		<el-button type="primary" plain @click="open">导出</el-button>
	</slot>

  <el-drawer v-model="dialog" title="导出" :size="400" direction="rtl" append-to-body destroy-on-close>
		<el-main style="padding: 0 20px 20px 20px;">
			<div v-loading="downLoading" element-loading-text="正在处理中...">
				<div 
          v-if="downLoading && progress" 
          style="position: absolute;width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;z-index: 3000;"
        >
					<el-progress  
            :text-inside="true" 
            :stroke-width="20" 
            :percentage="downLoadProgress" 
            style="width: 100%;margin-bottom: 120px;"
          />
				</div>
				<el-tabs>
					<el-tab-pane label="常规" lazy>
						<el-form label-width="100px" label-position="left" style="margin: 10px 0 20px 0;">
							<el-form-item label="文件名">
								<el-input v-model="formData.fileName" placeholder="请输入文件名" />
							</el-form-item>
							<el-form-item label="文件类型">
								<el-select v-model="formData.fileType" placeholder="请选择文件类型">
									<el-option v-for="item in fileTypes" :key="item" :label="'*.'+item" :value="item" />
								</el-select>
							</el-form-item>
							<slot name="form" :formData="formData"></slot>
						</el-form>
						<el-button type="primary" size="large" icon="el-icon-download" style="width: 100%;" @click="download">下 载</el-button>
					</el-tab-pane>
					<el-tab-pane label="列设置" v-show="columnData.length" lazy>
						<ExportColums :column="columnData" />
					</el-tab-pane>
					<el-tab-pane label="其他参数" v-if="data" lazy>
						<el-descriptions :column="1" border size="small">
							<el-descriptions-item v-for=" (val, key) in data" :key="key" :label="key">{{val}}</el-descriptions-item>
						</el-descriptions>
					</el-tab-pane>
				</el-tabs>
			</div>
		</el-main>
	</el-drawer>
</template>

<script setup>
import {ref, watch} from 'vue'
import {ElNotification} from 'element-plus'
import ExportColums from './ExportColums'

// eslint-disable-next-line no-undef
const props = defineProps({
  fileName: {type: String, default: ''},
  apiObj: {type: Object, default: () => {}},
  data: {type: Object, default: () => {}},
  fileTypes: {type: Array, default: () => ['xlsx']},
  column: {type: Array, default: () => []},
  blob: {type: Boolean, default: false},
  progress: {type: Boolean, default: true}
})

const dialog = ref(false)
const formData = ref({
  fileName: props.fileName,
  fileType: props.fileTypes[0]
})
const columnData = ref([])
const downLoading = ref(false)
const downLoadProgress = ref(0)

watch(() => formData.value.fileType, newType => {
  const filename = formData.value.fileName
  if (filename.includes('.')) {
    formData.value.fileName = filename.substring(0, filename.lastIndexOf('.')) + '.' + newType
  } else {
    formData.value.fileName = filename +'.' + newType
  }
})

function open() {
  const p = props
  dialog.value = true
  formData.value = {
    fileName: (p.fileName ? p.fileName : (new Date().getTime() + '')) + '.' + p.fileTypes[0],
    fileType: p.fileTypes[0]
  }
  columnData.value = JSON.parse(JSON.stringify(p.column))
}
function close() {
  dialog.value = false
}
function download() {
  const p = props
  const formDataVal = formData.value
  let columnArr = {
    column: columnData.value.filter(n => !n.hide).map(n => n.prop).join(',')
  }
  let assignData = {...p.data, ...formDataVal, ...columnArr}
  if (p.blob) {
    downloadFile(p.apiObj, formDataVal.fileName, assignData)
  } else {
    linkFile(p.apiObj.url, formDataVal.fileName, assignData)
  }
}
function linkFile(url, fileName, data = {}) {
  commonDownload('linkFile', url + toQueryString(data))
  // let a = document.createElement('a')
  // a.style = 'display: none'
  // a.target = '_blank'
  // a.href = url + toQueryString(data)
  // document.body.appendChild(a)
  // a.click()
  // document.body.removeChild(a)
}
function downloadFile(apiObj, fileName, data = {}) {
  downLoading.value = true
  apiObj.get(data, {
    responseType: 'blob',
    onDownloadProgress(e){
      if (e.lengthComputable) {
        downLoadProgress.value = parseInt(e.loaded / e.total * 100)
      }
    }
  }).then(res => {
    downLoading.value = false
    downLoadProgress.value = 0
    const url = URL.createObjectURL(res)
    commonDownload('download', url, fileName)
    // const a = document.createElement('a')
    // a.style = 'display: none'
    // a.target = '_blank'
    // a.download = fileName
    // a.href = url
    // document.body.appendChild(a)
    // a.click()
    // document.body.removeChild(a)
    // URL.revokeObjectURL(url)
  }).catch(err => {
    downLoading.value = false
    downLoadProgress.value = 0
    ElNotification.error({
      title: '下载文件失败',
      message: err
    })
  })
}
function commonDownload(type = 'linkFile', url, fileName) {
  const a = document.createElement('a')
  a.style = 'display: none'
  a.target = '_blank'
  if (type === 'download') {
    a.download = fileName
  }
  a.href = url
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  if (type === 'download') {
    URL.revokeObjectURL(url)
  }
}
function toQueryString(obj){
  let arr = []
  for (const k in obj) {
    arr.push(`${k}=${obj[k]}`)
  }
  return (arr.length > 0 ? '?' : '') + arr.join('&')
}

// eslint-disable-next-line no-undef
defineExpose({close})
</script>
